<template>
  <yt-page title="指令记录" scroll :rightData="rightData">
    <yt-card v-for="(item,index) of actions" :key="index" class="no-padding" :tag="false" :title="item.Time | formatTime">
      <div slot="more">
        <yt-btn theme="red" size="mini" :loading="(loaded) => remove(item.index, loaded)">删除</yt-btn>
      </div>
      <yt-textarea title="执行步骤" type="row" v-model="item.context" disabled></yt-textarea>
      <yt-cell-open-file class="file-item" v-for="(f,i) of item.file" :key="i" :title="f.name" :url="f.url">
        {{f.name}}
      </yt-cell-open-file>
    </yt-card>
  </yt-page>
</template>

<script>
import { EVENTS, BUS } from '@/store' // 依赖各个安监项目下独立的 store
import { commonApi } from '@/common/api/commonApi.js'
import { InstructionRecordAdd } from './router'

export default {
  data() {
    return {
      emergencyObj: {},
      actions: [],
      rightData: [
        {
          font: 'yt-icon yt-icon-add',
          click: () => {
            this.$router.$push({
              path: InstructionRecordAdd.path,
              query: {
                ...this.$route.query
              }
            })
          }
        }
      ]
    }
  },
  created() {
    BUS.$on(EVENTS.emergencyCommandActionAdd, async form => {
      this.actions.push({ ...form })
      this.updateActions()
    })
  },
  activated() {
    if (this.$router.$isBack) return
    this.queryActions()
  },
  methods: {
    async queryActions() {
      let actionsBefor = await commonApi.search('yj_instruction_record', {
        equalTo: {
          index: this.$route.query.index,
          programmeId: this.$route.query.programmeId,
          accidentId: this.$route.query.accidentId
        }
      })
      let arr = []
      actionsBefor.map(v => {
        v.list.map(h => {
          arr.push(h)
        })
      })
      this.actions = arr
    },
    async remove(index, loaded) {
      this.actions.splice(index, 1)
      await this.updateActions()
      loaded
    },
    async updateActions() {
      let obj = {
        accidentId: this.$route.query.accidentId,
        programmeId: this.$route.query.programmeId,
        index: parseInt(this.$route.query.index),
        list: this.actions
      }
      commonApi
        .search('yj_instruction_record', {
          equalTo: {
            index: parseInt(this.$route.query.index),
            programmeId: this.$route.query.programmeId,
            accidentId: this.$route.query.accidentId
          }
        })
        .then(res => {
          res = res.map(v =>
            commonApi.createInstance('yj_instruction_record', v.id)
          )
          commonApi.destroyAll(res).then(res => {
            commonApi.save('yj_instruction_record', obj).then(res => {
              this.$Toast('操作成功!', 'success')
            })
          })
        })
    }
  }
}
</script>

<style scoped lang="stylus">
.no-padding >>> .yt-card-body
  padding 0

>>> .yt-card-header
  align-items center

.file-item
  padding 10px
</style>
